package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    @Transactional
    public void submit(Orders orders) {
        //然后在OrderServiceImpl中完成下单功能的具体实现，下单功能的具体逻辑如下：
        //A. 获得当前用户id, 查询当前用户的购物车数据,获取购物车对象集
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> spLqw = new LambdaQueryWrapper<>();
        spLqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shopList = shoppingCartService.list(spLqw);

        if (shopList == null || shopList.size() == 0) {
            throw new CustomException("购物车为空,不能下单");
        }

        //B. 根据当前登录用户id, 查询用户数据,获取用户对象
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("用户为空");
        }

        //C. 根据地址ID, 查询地址数据,获取地址对象
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        if (address == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }

        // 获取或者说创建订单号  使用IdWorker.getId() 方法获得一个订单号
        long orderId = IdWorker.getId();


        //AtomicInteger amount = new AtomicInteger(0);  创建一个初始值为0的整数类型对象,累计添加价格进行结算
        AtomicInteger amount = new AtomicInteger(0);


        //D. 组装订单明细数据, 批量保存订单明细,用流来循环保存订单的菜品套餐数据
        List<OrderDetail> orderDetailList = shopList.stream().map((shop) -> {
            // new 一个 订单明细对象,并往里面设置属性
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            // 拷贝购物车集合中的一个对象给新建的明细对象
            BeanUtils.copyProperties(shop, orderDetail);
            // 钱要自己算一下multiply乘  intvalue
            Integer number = orderDetail.getNumber();
            BigDecimal odAmount = orderDetail.getAmount();
            // BigDecimal
            BigDecimal money = odAmount.multiply(new BigDecimal(number));
            amount.addAndGet(money.intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //E. 组装订单数据, 批量保存订单数据  慢慢的set数据
        orders.setId(orderId);
        orders.setNumber(toString().valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setAddress(
                (address.getProvinceName() == null ? "" : address.getProvinceName())
                +(address.getCityName() == null ? "" : address.getCityName())
                +(address.getDistrictName() == null ? "" : address.getDistrictName())
                +(address.getDetail() == null ? "" : address.getDetail())
        );
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.intValue()));
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());

        // 向订单表插入数据，一条数据
        save(orders);
        // 向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetailList);
        //F. 删除当前用户的购物车列表数据
        shoppingCartService.remove(spLqw);
    }

    @Override
    public void again(Orders orders) {
        // 从 orders的id里找到对应的明细数据集
        Long ordersId = orders.getId();
        LambdaQueryWrapper<OrderDetail> odlqw = new LambdaQueryWrapper<>();
        odlqw.eq(OrderDetail::getOrderId, ordersId);
        List<OrderDetail> odList = orderDetailService.list(odlqw);
        //  把明细数据集里的内容传给了购物车
        List<ShoppingCart> list = odList.stream().map(orderDetail -> {
            ShoppingCart cart = new ShoppingCart();
            orderDetail.setId(null);
            BeanUtils.copyProperties(orderDetail, cart);
            cart.setId(null);
            cart.setCreateTime(LocalDateTime.now());
            cart.setUserId(BaseContext.getCurrentId());
            return cart;
        }).collect(Collectors.toList());

        // 添加购物车
        shoppingCartService.saveBatch(list);

    }
}